/**
  * @Description: 施工填报  ===>  建转运填报/施工填报
  * @author zhangxia
  */

<template>
  <view class="task-monitor-main">
    <nav-bar class="header" back :title="titleName" @goBack="goBack"></nav-bar>
    <view class="contentwrap">
      <view class="header-bar">
        <!-- 切换tab -->
        <view class="get-state-tab">
          <view class="info-tab-item" :class="currentTab === 'non-executed' ? ' info-tab-current': ''" @click="tabChange('non-executed')">施工填报</view>
          <view class="info-tab-item" :class="currentTab === 'executed' ? ' info-tab-current': ''" @click="tabChange('executed')">建转运填报</view>
        </view>
      </view>
      <view class="content" v-if="currentTab === 'non-executed' && !isNotChecked">
        <view class="commonItem" v-for="(item,i) in fillData" :key="i">
          <view class="commontitle">{{item.title}}</view>
          <view class=" commonbj isconcealed">

            <van-field disabled v-model="item.selectName" :label="item.selectTitle"
               :rules="[{ required: false}]" input-align="right"
              :placeholder="`请选择${item.selectTitle}`" right-icon="arrow"
              @click-right-icon="handleSelect(item, i)" />
          </view>
          <view class="commonbj">
            <template v-if="!item.isSelect">
              <view class="signintitle">
                <view class="notes">不执行说明</view>
                <view class="notes-tips">
                  <view :class="[item.notesTipIdx==0?'active':'', 'tips-item']" @click="notesTipClick(0,i)">无本项工作</view>
                  <view :class="[item.notesTipIdx==1?'active':'', 'tips-item']" @click="notesTipClick(1,i)">无需执行此操作</view>
                </view>
                <view class="notestext">
                  <van-field v-model="item.notes" rows="3" autosize label="" type="textarea" placeholder="请输入不执行说明" class="textarea" />
                </view>
              </view>
            </template>
            <template v-else>
              <view class="equipmenttitle">
                设备照片
              </view>
              <view class="image-wrap">
                <view class="image-list">
                  <view class="upload-button"
                        v-for="(imgItem, index) in item.fileList"
                        :style="{'background-image': `url(${imgItem.bgImg})`}"
                        :key="index" @click.stop="imageHandle(index,imgItem,'CHOOSE',i)">
                    <view v-if="imgItem.img" class="delete-icon" @click.stop="imageHandle(index,imgItem, 'DELETE',i)">
                      ×</view>
                    <img v-if="imgItem.img" :src="imgItem.img" alt="" @click.stop="imageHandle(index,imgItem, 'PREVIEW',i)">
                    <view v-if="imgItem.img" class="small-title">{{imgItem.previewName}}</view>
                  </view>

                </view>

              </view>
            </template>

          </view>
        </view>
      </view>
	  <view class="content" v-if="currentTab === 'non-executed' && isNotChecked">
	    <view class="commonItem" v-for="(item,i) in fillData" :key="i">
	      <view class="commontitle">{{item.title}}</view>
	      <view class=" commonbj isconcealed">

	        <van-field disabled v-model="item.selectName" :label="item.selectTitle"
	           :rules="[{ required: false}]" input-align="right"
	          :placeholder="`请选择${item.selectTitle}`" right-icon="arrow"
	         />
	      </view>
	      <view class="commonbj">
	        <template v-if="!item.isSelect">
	          <view class="signintitle">
	            <view class="notes">不执行说明</view>
	            <view class="notestext">
	              <van-field v-model="item.notes" disabled rows="3" autosize label="" type="textarea" placeholder="请输入不执行说明" class="textarea" />
	            </view>
	          </view>
	        </template>
	        <template v-else>
	          <view class="equipmenttitle">
	            设备照片
	          </view>
	          <view class="image-ready-wrap">
              <view class="image-item" v-for="(imgItem,imgIndex) in item.fileList" :key="imgIndex">
                <img v-if="imgItem.img" :src="imgItem.img" alt="" @click.stop="imageHandle(index,imgItem, 'PREVIEW',i)">
                <view v-if="imgItem.img" class="small-title">{{imgItem.previewName}}</view>
              </view>
	          </view>


	        </template>

	      </view>
	    </view>
	  </view>
      <view class="content" v-else-if="currentTab === 'executed' ">
        <view class="commontitle">建转运信息</view>
        <view class="commonbj isledger">
          <van-field disabled v-model="isConcealed" label="台账维护方式" :rules="[{ required: true}]" placeholder="请选择台账维护方式" right-icon="arrow" @click-right-icon="handleSelect('ledger')" />
        </view>
        <view class="commonbj">
          <van-cell-group>
            <van-field label="设备名称" v-model="equipmentName" readonly input-align="right" />
            <van-field disabled v-model="equipment" label="设备名称" :rules="[{ required: true}]" placeholder="请选择" right-icon="arrow" input-align="right" @click-right-icon="handleSelect('equipment')" />
            <van-field disabled v-model="siteName" label="所属站点" :rules="[{ required: true}]" placeholder="请选择" right-icon="arrow" input-align="right" @click-right-icon="handleSelect('site')" />
            <van-field :disabled="isDisabled" v-model="siteType" label="所属站点类型" :rules="[{ required: true}]" placeholder="请选择" right-icon="arrow" input-align="right"
              @click-right-icon="handleSelect('sitetype')" />
          </van-cell-group>
        </view>
      </view>
    </view>
    <footer v-if="!isNotChecked">
      <van-button block native-type="submit" @click="verifyHandle">保存</van-button>
    </footer>
    <!--工程名称选择器-->
    <van-popup v-model="showPicker" position="bottom">
      <van-picker :title="pickerName" ref="typePicker" show-toolbar :columns="projectColumns" @confirm="onConfirm" @cancel="showPicker = false" />
    </van-popup>
  <!-- 拍照预览   -->
    <van-popup class="van-preview-wrap" v-model="showPreview" @click="showPreview = false">
      <van-swipe>
        <div v-for="(image, index) in files" :key="index">
          <van-swipe-item v-if="image.img" style="text-align: center;">
            <img :src="image.img" />
          </van-swipe-item>
        </div>
      </van-swipe>
    </van-popup>
  </view>
</template>

<script>
import config from "../../../../common/config";
import navBar from '../../../../components/common/nav-bar'
import wx from '../../../../static/common_js/jweixin_1.0.0'
import { Dialog, Toast } from 'vant'
import axios from 'axios'
import {merge} from "lodash";
import { mapGetters } from "vuex";
import { process } from '../../../../api/apiIndex';
import { isBase64, removeBaseUrl } from "../../../../utils"


export default {
  name: 'filling',
  components: { navBar },
  props: {},
  data() {
    return {
      baseUrl: "", // 基础url
      showPreview: false,
      titleName: '',
      currentTab: 'non-executed',
      currentIndex: '0',
      isConcealed: '',
      showPicker: false,
      pickerName: '是否安装',
      projectColumns: [
        {
          values: ['否', '是'],
          defaultIndex: 0
        }
      ],
      files: [],
      notes: '',
      isDisabled: true,
      siteType: '',
      equipmentName: '',
      equipment: '',
      siteName: '',
      picIndex: '0',
      curType: '',
      curTypeIndex: 0,
      fillData: [
        {
          title: '安装',
          selectTitle: '是否安装',
          selectName: '是',
          isSelect: 1, // 0-否 1-是
          fileList: [
            {
              img: '',
              raw: null,
              type: '',
              previewName: "资产全貌",
              bgImg: require("../../../../static/img/bg_zcqm.png"),
            },
            {
              img: '',
              raw: null,
              type: '',
              previewName: "铭牌照片",
              bgImg: require("../../../../static/img/bg_mpzp.png"),
            },
            {
              img: '',
              raw: null,
              type: '',
              bgImg: require("../../../../static/controlImg/bg_pz.png"),
            }
          ],
          notesTipIdx: 0,
          notes: ''
        },
        {
          title: '单机调试',
          selectTitle: '是否单机调试',
          selectName: '是',
          isSelect: 1, // 0-否 1-是
          fileList: [
            {
              img: '',
              raw: null,
              type: '',
              bgImg: require("../../../../static/controlImg/bg_pz.png"),
            }
          ],
          notesTipIdx: 0,
          notes: ''
        },
        {
          title: '联网调试',
          selectTitle: '是否联网调试',
          selectName: '否',
          isSelect: 0, // 0-否 1-是
          fileList: [
            {
              img: '',
              raw: null,
              type: '',
              bgImg: require("../../../../static/controlImg/bg_pz.png"),
            }
          ],
          notesTipIdx: 0,
          notes: ''
        },
		    {
          title: '隐蔽施工',
          selectTitle: '是否隐蔽施工',
          selectName: '否',
          isSelect: 0, // 0-否 1-是
          fileList: [
            {
              img: '',
              raw: null,
              type: '',
              bgImg: require("../../../../static/controlImg/bg_pz.png"),
            }
          ],
          notesTipIdx: 0,
          notes: ''
        }
      ],
      equId: '', // 设备id
      neSn: '', // 设备名称
      engId: '' ,// 工程id,
	    isNotChecked: false, // 编辑false还是查看true
      procss: 0,
      examFlag: '0',  // 是否提交审核 1-是 0-否
      fileFormData: null,
			imgBase64: ''


    }
  },
  created() {},
  mounted() {},
  onLoad(option) {
    this.titleName = option.name
    config.getOptions.then(res => {
      this.baseUrl = res.firstUrl;
      // this.baseUrl = 'http://192.168.0.127:18001';
    })
    if (option.index === '0') {
      this.currentTab = 'non-executed'
    } else {
      this.currentTab = 'executed'
    }
    if(option.status === '已提交'){
      this.isNotChecked = true;
    }else{
      this.isNotChecked = false;
    }
    this.tabChange(this.currentTab)
    this.equId = option.equId // 设备id
    this.neSn = option.neSn // 设备名称
    this.engId = option.engId // 工程id

    this.loadFillDetail(this.equId)
  },
  computed: {
    ...mapGetters(["userData",'txgkAuth'])
  },
  watch: {},
  methods: {
    notesTipClick(i,idx){
      this.fillData[idx].notesTipIdx = i
      let strArr = ['无本项工作', '无需执行此操作']
      this.fillData[idx].notes = strArr[i]
    },
    setFillFile(arr, i) {  // 编辑和只读下图片的设置
      this.fillData[i].fileList = []
      let preName = ''

      arr.forEach((item, index) => {

        if (i == 0) {
          if(index == 0) {preName ='资产全貌'} else if (index == 1){preName ='铭牌照片'}
          else  {preName =''}
        }
        this.fillData[i].fileList.push({
          img: this.baseUrl + item.furl,
          raw: null,
          type: item.fl,
          previewName: preName,
          bgImg: require("../../../../static/controlImg/bg_pz.png"),
        })

        // if (this.isNotChecked) { // 查看
        //   this.fillData[i].fileList.push({
        //     img: this.baseUrl + item.furl,
        //     raw: null,
        //     type: item.fl,
        //     bgImg: require("../../../../static/controlImg/bg_pz.png"),
        //   })
        // } else { // 编辑
        //   this.getImageUrlBase64(this.baseUrl + item.furl).then(res => {
        //     this.fillData[i].fileList.unshift({
        //       img: this.baseUrl + item.furl,
        //       raw: res.file,
        //       type: item.fl,
        //       bgImg: require("../../../../static/controlImg/bg_pz.png"),
        //     })
        //   })
        // }
      })
      if (!this.isNotChecked) {
        if (this.fillData[i].fileList.length < 9) { // 最多上传9张 不够添加空对象
          this.fillData[i].fileList.push({
            img: '',
            raw: null,
            type: '',
            bgImg: require("../../../../static/controlImg/bg_pz.png"),
          })
        }
      }
    },
    loadFillDetail(objId) {
      let params = {
        objId
      }
      this.$apiRequest.gcgkApi.fillDetail(params).then(res => {
        var obj = res.data[0]

        merge(this.fillData[0], {
          isSelect: obj.isInstall !== undefined ? Number(obj.isInstall) : 1,
          selectName: obj.isInstall !== undefined ? Number(obj.isInstall)===1?'是':'否': '是'
        })
        merge(this.fillData[1], {
          isSelect: obj.isAlone !== undefined ? Number(obj.isAlone): 1,
          selectName: obj.isAlone !== undefined ? Number(obj.isAlone)===1?'是':'否': '是'
        })
        merge(this.fillData[2], {
          isSelect: obj.isNetwork !== undefined ? Number(obj.isNetwork) : 0,
          selectName: obj.isNetwork !== undefined ? Number(obj.isNetwork)===1?'是':'否' :  '否'
        })
        merge(this.fillData[3], {
          isSelect: obj.isHide !== undefined ? Number(obj.isHide) : 0,
          selectName: obj.isHide !== undefined ? Number(obj.isHide)===1?'是':'否' : '否'
        })
        // 备注
        this.fillData[0].notes = obj.installNotes
        this.fillData[1].notes = obj.aloneNotes
        this.fillData[2].notes = obj.networkNotes
        this.fillData[3].notes = obj.hideNotes

        if (obj.installFileList&&obj.installFileList.length > 0) {
          this.setFillFile(obj.installFileList, 0)
        }
        if (obj.aloneFileList&&obj.aloneFileList.length > 0) {
          this.setFillFile(obj.aloneFileList, 1)
        }
        if (obj.networkFileList&&obj.networkFileList.length > 0) {
          this.setFillFile(obj.networkFileList, 2)
        }
        if (obj.hideFileList&&obj.hideFileList.length > 0) {
          this.setFillFile(obj.hideFileList, 3)
        }
      })
    },
    tabChange(currentTab) {
      
      if(this.txgkAuth === 'SUPERVISOR_PERSON' && currentTab === 'executed')return;
	   this.currentTab = currentTab
	   currentTab === 'executed' && (this.currentIndex = '1')
	   currentTab === 'non-executed' && (this.currentIndex = '0')
      // this.onRefresh()
    },
    handleSelect(e, index) {
      console.log(e,index)
      this.curTypeIndex = index
      this.projectColumns[0].defaultIndex = e.isSelect
      this.pickerName = e.selectTitle
      this.showPicker = true
    },
    onConfirm(value, index) {
      this.$set(this.fillData[this.curTypeIndex], 'selectName', value[0])
      this.$set(this.fillData[this.curTypeIndex], 'isSelect', value[0] === '是' ? 1 : 0)
      // this.$forceUpdate()
      if (this.fillData[this.curTypeIndex].isSelect === 1) {
        if(this.curTypeIndex == 0) { // 安装下
          this.$set(this.fillData[this.curTypeIndex], 'fileList', [{
              img: '',
              raw: null,
              type: '',
              previewName: "资产全貌",
              bgImg: require("../../../../static/img/bg_zcqm.png"),
            },
            {
              img: '',
              raw: null,
              type: '',
              previewName: "铭牌照片",
              bgImg: require("../../../../static/img/bg_mpzp.png"),
            },
            {
              img: '',
              raw: null,
              type: '',
              bgImg: require("../../../../static/controlImg/bg_pz.png"),
            }])
        } else {
          this.$set(this.fillData[this.curTypeIndex], 'fileList', [{img: '', raw: null,type: '',bgImg: require('../../../../static/controlImg/bg_pz.png')}])
        }
      } else {
        this.$set(this.fillData[this.curTypeIndex], 'notes', '')
      }
      this.showPicker = false
    },
    imageHandle(imgIndex, imgItem, handleType, i) {

      this.curTypeIndex = i
      if (handleType === 'CHOOSE') {
        this.choosePhoto(imgIndex, imgItem)
      } else if (handleType === 'PREVIEW') {
        this.files = [imgItem]
        this.showPreview = true
      } else if (handleType === 'DELETE') {
        Dialog.confirm({
          title: `是否确认删除`
        })
          .then(() => {
            let fileTempList = [
              {
              img: '',
              raw: null,
              type: '',
              previewName: "资产全貌",
              bgImg: require("../../../../static/img/bg_zcqm.png"),
            },
            {
              img: '',
              raw: null,
              type: '',
              previewName: "铭牌照片",
              bgImg: require("../../../../static/img/bg_mpzp.png"),
            },
            {
              img: '',
              raw: null,
              type: '',
              bgImg: require("../../../../static/controlImg/bg_pz.png"),
            }]
            if(this.curTypeIndex != 0) {
              this.fillData[this.curTypeIndex].fileList.splice(imgIndex, 1)
            } else { // 安装下
              if(imgIndex>1) {
                this.fillData[this.curTypeIndex].fileList.splice(imgIndex, 1)
              }else {
                this.$set(this.fillData[this.curTypeIndex].fileList, imgIndex, fileTempList[imgIndex])
              }
            }
            if (this.fillData[this.curTypeIndex].fileList.length < 9) { // 最多上传9张 不够添加空对象
              if (this.fillData[this.curTypeIndex].fileList[this.fillData[this.curTypeIndex].fileList.length-1].img) {
                this.fillData[this.curTypeIndex].fileList.push({img: '',raw: null,type: '',bgImg: require("../../../../static/controlImg/bg_pz.png"),})
              }
            }

          })
          .catch(() => {
            // on cancel
          })
      }
    },
    choosePhoto1(imgIndex, imgItem){
      let _this = this

      const photoName = `${new Date().getTime()}`
      if (_this.curTypeIndex != 0) {
        _this.$set(
          _this.fillData[_this.curTypeIndex].fileList,
          imgIndex,
          {
            raw: _this.dataURLtoFile(this.imgBase64, `${photoName}.jpeg`),
            img: this.imgBase64,
            type: imgItem.type,
          }
        )
      } else {  // 安装下
        if (imgIndex > 1) {
          _this.$set(
            _this.fillData[_this.curTypeIndex].fileList,
            imgIndex,
            {
              raw: _this.dataURLtoFile(this.imgBase64, `${photoName}.jpeg`),
              img: this.imgBase64,
              type: imgItem.type,
            }
          )
        } else  {
          _this.$set(
            _this.fillData[_this.curTypeIndex].fileList,
            imgIndex,
            {
              ..._this.fillData[_this.curTypeIndex].fileList[imgIndex],
              raw: _this.dataURLtoFile(this.imgBase64, `${photoName}.jpeg`),
              img: this.imgBase64,
              type: imgItem.type,
            }
          )
        }
      }
      if (_this.fillData[_this.curTypeIndex].fileList.length < 9) {
        // 最多上传9张 不够添加空对象
        if (_this.fillData[_this.curTypeIndex].fileList[_this.fillData[_this.curTypeIndex].fileList.length-1].img) {
          _this.fillData[_this.curTypeIndex].fileList.push({img: '', raw: null, type: '', bgImg: require("../../../../static/controlImg/bg_pz.png")})
        }
      }
    },
    choosePhoto(imgIndex, imgItem) {
      let _this = this
      wx.chooseImage({
        count: 1,
        sourceType: ['album','camera'],
        success: chooseImageRes => {
          wx.getLocalImgData({
            localId: chooseImageRes.localIds[0].toString(),
            success: function (res) {
              const localData = res.localData
              let imageBase64 = ''
              if (localData.indexOf('data:image') == 0) {
                //苹果的直接赋值，默认生成'data:image/jpeg;base64,'的头部拼接
                imageBase64 = localData
              } else {
                //此处是安卓中的唯一得坑！在拼接前需要对localData进行换行符的全局替换
                //此时一个正常的base64图片路径就完美生成赋值到img的src中了
                imageBase64 =
                  'data:image/jpeg;base64,' + localData.replace(/\n/g, '')
              }

              const photoName = `${new Date().getTime()}`
              if (_this.curTypeIndex != 0) {
                _this.$set(
                  _this.fillData[_this.curTypeIndex].fileList,
                  imgIndex,
                  {
                    raw: _this.dataURLtoFile(imageBase64, `${photoName}.jpeg`),
                    img: imageBase64,
                    type: imgItem.type,
                  }
                )
              } else {  // 安装下
                if (imgIndex > 1) {
                  _this.$set(
                    _this.fillData[_this.curTypeIndex].fileList,
                    imgIndex,
                    {
                      raw: _this.dataURLtoFile(imageBase64, `${photoName}.jpeg`),
                      img: imageBase64,
                      type: imgItem.type,
                    }
                  )
                } else  {
                  _this.$set(
                    _this.fillData[_this.curTypeIndex].fileList,
                    imgIndex,
                    {
                      ..._this.fillData[_this.curTypeIndex].fileList[imgIndex],
                      raw: _this.dataURLtoFile(imageBase64, `${photoName}.jpeg`),
                      img: imageBase64,
                      type: imgItem.type,
                    }
                  )
                }
              }
              if (_this.fillData[_this.curTypeIndex].fileList.length < 9) {
                // 最多上传9张 不够添加空对象
                if (_this.fillData[_this.curTypeIndex].fileList[_this.fillData[_this.curTypeIndex].fileList.length-1].img) {
                  _this.fillData[_this.curTypeIndex].fileList.push({img: '', raw: null, type: '', bgImg: require("../../../../static/controlImg/bg_pz.png")})
                }
              }
            }
          })
        },
        fail: error => {}
      })
    },
    dataURLtoFile(dataurl, filename) {
      var arr = dataurl.split(','),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      return new File([u8arr], filename, { type: mime })
    },
    h5_url_to_blob(url) {
      let arr = url.split(',')
      let mime = arr[0].match(/:(.*?);/)[1]
      let bstr = atob(arr[1])
      let n = bstr.length
      let u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      return new Blob([u8arr], {
        type: mime
      })
    },

    /**@url :图片服务器上的url
     * @img :图片url对应的图片
     * */
    // toBase64(img) {
    //   const canvas = document.createElement('canvas') //创建一个canvas元素
    //   canvas.width = img.width //把当前url对应的图片的宽度赋予canvas
    //   canvas.height = img.height //把当前url对应的图片的高度赋予canvas
    //   const ctx = canvas.getContext('2d')
    //   ctx.drawImage(img, 0, 0, canvas.width, canvas.height) //在画布上一比一的画出img
    //   const base64 = canvas.toDataURL('image/jpeg') //调用canvas的toDataURL获取.jpg的base64数据
    //   return base64
    // },
    // getImageUrlBase64(url) {
    //   return new Promise((resolve, reject) => {
    //     const img = new Image()

    //     img.onload = () => {
    //       let photoName = `${new Date().getTime()}`
    //       var file = this.dataURLtoFile(this.toBase64(img), `${photoName}.jpeg`)
    //       resolve({img: this.toBase64(img), file})
    //       // return this.toBase64(img);
    //     }
    //     img.src = url
    //     img.crossOrigin = 'anonymous' //处理跨域，后端也要设置跨域处理才行
    //   })
    // },

    verifyHandle(){
      this.procss = 0
      if (this.fillData[0].isSelect) {
        if (!this.fillData[0].fileList[0].img) {
          Toast.fail('安装下必须上传资产全貌')
          return
        }
        if (!this.fillData[0].fileList[1].img) {
          Toast.fail('安装下必须上传铭牌照片')
          return
        }
      }
      for(var i = 0, len = this.fillData.length; i < len; i++) {
        if (this.fillData[i].isSelect) {
          if(i === 0) {
            if (this.fillData[i].fileList.length > 2) {
              this.procss++
            }
          } else {
            if (this.fillData[i].fileList.length > 1) {
              this.procss++
            }
          }
        } else {
          if (this.fillData[i]?.notes&&this.fillData[i].notes.length>0) {
            this.procss++
          }
        }
      }
      if (this.procss == 4) {// 全部填写
        Dialog.confirm({
          message: "是否直接提交审核",
          confirmButtonText: "是",
          cancelButtonText: "否"
        }).then(() => {
          this.examFlag = '1'
          this.goSave()
        }).catch(() => {
          this.examFlag = '0'
          this.goSave()
        });
      } else {
        this.examFlag = '0'
        this.goSave()
      }
    },
    goSave() {
      Toast.loading({
        duration: 0,
        message: '加载中...',
        forbidClick: true
      })
      var params = {
        objId: this.equId, //设备id
        engId: this.engId, //工程id
        // "engQuantityId": "",//工程量id
        // "engName": "",//工程名称
        // "engrItems": "",//工程项大类id
        // "engrItemsName": "",//工程项大类名称
        // "engrType": "",//工程项小类id
        // "engrTypeName": "",//工程项小类名称
        // "neType": "",//设备类型id
        // "neTypeName": "",//设备类型名称
        neSn: this.neSn, //设备名称

        isInstall: this.fillData[0].isSelect, //是否安装 0-否 1-是
        isAlone: this.fillData[1].isSelect, //单机调试  0-否 1-是
        isNetwork: this.fillData[2].isSelect, //联网调试  0-否 1-是
        isHide: this.fillData[3].isSelect, //是否存在隐蔽施工  0-否 1-是

        hideNotes: '', //隐蔽备注
        installNotes: '', //安装备注
        aloneNotes: '', //单机调试备注
        networkNotes: '', //联网备注

        fillUser: this.userData.USERID,
        fillUsername:  this.userData.USERNAME,
        examFlag: this.examFlag,

        hideStatus: 0,
        installStatus: 0,
        aloneStatus: 0,
        networkStatus: 0
      }
      var formData = new FormData()
		  this.fileFormData = new FormData()
      this.fillData.forEach((item, index) => {

        if (item.isSelect == 1) {
          let furlArr = []
          if (index == 0) {
              // 是否安装
              this.fileFormData.append(`requests[${index}].fl`, 2)  // 文件分类(类型)
              if (item.fileList.length>1){ params.installStatus=1 }
          } else if (index == 1) {
            // 单机调试
            this.fileFormData.append(`requests[${index}].fl`, 3)  // 文件分类(类型)
            if (item.fileList.length>1){ params.aloneStatus=1 }
          } else if (index == 2) {
            // 联网调试
            this.fileFormData.append(`requests[${index}].fl`, 4)  // 文件分类(类型)
            if (item.fileList.length>1){ params.networkStatus=1 }
          } else if (index == 3) {
            // 隐蔽施工
            this.fileFormData.append(`requests[${index}].fl`, 1)  // 文件分类(类型)
            if (item.fileList.length>1){ params.hideStatus=1 }
          }
          item.fileList.forEach((e,i,arr) => {
            // if (e.raw) formData.append('installFileList', e.raw)
            if(e.img){ // 去除最后一个
              if (isBase64(e.img)) {// 新拍照
                if (e.raw) {
                  this.fileFormData.append(`requests[${index}].requests[${i}].file`, e.raw)
                  this.fileFormData.append(`requests[${index}].requests[${i}].flag`, i+1)
                }
              } else { // 旧照
                this.fileFormData.append(`requests[${index}].requests[${i}].furl`, removeBaseUrl(e.img, this.baseUrl))
                this.fileFormData.append(`requests[${index}].requests[${i}].flag`, i+1)
                // if (e.img) furlArr.push(removeBaseUrl(e.img, this.baseUrl))
              }
            }
          })
          // this.fileFormData.append(`requests[${index}].furls`, furlArr.join())
          this.fileFormData.append(`requests[${index}].sfzx`, 1) // 整改后
          this.fileFormData.append(`requests[${index}].jlid`, this.equId)

        } else {
          if (index == 0) {
            // 是否安装
            params.installNotes = item.notes
          } else if (index == 1) {
            // 单机调试
            params.aloneNotes = item.notes
          } else if (index == 2) {
            // 联网调试
            params.networkNotes = item.notes
          } else if (index == 3) {
            // 隐蔽施工
            params.hideNotes = item.notes
          }
        }
      })
      this.handleFileUploads()
      formData.append('fillDetail', JSON.stringify(params)) // 添加form表单中其他数据
      let config = {
        headers: {
          'Content-Type': 'multipart/form-data',
          Authorization: uni.getStorageSync('token') || ''
      }
      }
      let url = ''
      // #ifndef IGW
      url = '/ap/txgcgk/api/fillDetail/saveFillDetail'
      // #endif
      // #ifdef IGW
      // url = `http://192.168.124.75:18001/txgcgk/api/fillDetail/saveFillDetail`
      url = `${this.baseUrl}/txgcgk/api/fillDetail/saveFillDetail`
      // #endif

      axios.post(url, formData, config).then(res => {
        Toast.clear()
        if (res.data.code == 0) {
          Toast(this.examFlag == '1'?'提交成功':'保存成功')
          uni.navigateTo({
            url: `/pages/communicationControl/workbench/constructionFilling/index`
          })
        } else {
          Toast.clear()
          Toast(this.examFlag == '1'?'提交失败':'保存失败')
        }
      })
    },
    handleFileUploads(){
		  let config = {
		    headers: {
          'Content-Type': 'multipart/form-data',
          Authorization: uni.getStorageSync('token') || ''
        }
		  }

      let url = ''
		  // #ifndef IGW
		  url = '/ap/txgcgk/api/file/uploads'
		  // #endif
		  // #ifdef IGW
		  url = `${this.baseUrl}/txgcgk/api/file/uploads`
		  // url = `http://192.168.124.75:18001/txgcgk/api/file/uploads`
		  // #endif
		  axios.post(url, this.fileFormData, config).then(res => {
		    Toast.clear()
		    if (res.data.code == 0) {
		      Toast('提交成功')
		    } else {
		      Toast.clear()
		      Toast(res.data.msg)
		    }
		  })
    },
    goBack() {
      uni.navigateTo({
        url: '/pages/communicationControl/workbench/constructionFilling/index'
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.task-monitor-main {
  height: 100vh;
  background: #f2f6fa;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  .contentwrap {
    flex: 1;  
    overflow: hidden;
    display: flex;
    flex-direction: column;
    .header-bar {
      flex-shrink: 0;
      height: px2vh(220);
      background: #417adc;
      overflow: hidden;
      margin-top: px2vh(-1);
      .get-state-tab {
        width: calc(100% - #{px2vw(60)});
        height: px2vh(120);
        border-radius: px2vw(20);
        box-sizing: border-box;
        margin: px2vh(40) px2vw(30) px2vh(37);
        background-color: rgba(255, 255, 255, 0.4);
        display: flex;
        justify-content: center;
        align-items: center;
        border: px2vw(1) solid rgba(198, 215, 245, 1);
        .info-tab-item {
          width: 50%;
          display: flex;
          justify-content: center;
          align-items: center;
          color: rgba(255, 255, 255, 1);
          font-weight: bold;
          font-size: px2vw(38);
          &.info-tab-current {
            height: px2vh(100);
            margin: 0 px2vw(10);
            margin-right: px2vw(10);
            border-radius: px2vw(20);
            background-color: rgba(255, 255, 255, 0.7);
            color: rgba(65, 122, 220, 1);
            font-weight: Bold;
          }
        }
      }
    }
    .content {
      display: flex;
      flex-direction: column;
      flex: 1;
      overflow-y: scroll;
      box-sizing: border-box;
      padding: 0 px2vh(30);
      padding-top: px2vh(20);
      .commontitle {
        color: #666666;
        margin: px2vh(30) 0;
        font-weight: 700;
        font-size: px2vh(40);
      }
      .commonbj {
        background-color: #fff;
        margin-bottom: px2vh(30);
        border-radius: px2vh(20);
      }
      .commonItem {
        // width: 100vw;
        box-sizing: border-box;

        .commonbj {
          background-color: #fff;
          margin-bottom: px2vh(30);
          border-radius: px2vh(20);

          .image-wrap {
            width: 100%;
            display: flex;
            .image-list {
              width: 100%;
              display: flex;
              flex-wrap: wrap;
              padding: 0 px2vh(15) px2vh(60);
              box-sizing: border-box;
              img {
                width: px2vw(230);
                height: px2vw(230);
                border-radius: px2vw(6);
              }
              .upload-button {
                width: px2vw(230);
                height: px2vw(230);
                flex-shrink: 0;
                position: relative;
                background-size: 100% px2vw(230);
                margin: px2vh(49) calc((100% - #{px2vw(690)}) / 6) px2vh(60) calc((100% - #{px2vw(690)}) / 6);
                .typetext {
                  background-color: #fff;
                  position: absolute;
                  bottom: px2vh(-70);
                  left: calc(50% - #{px2vw(46)});
                  color: #dbdbdb;
                  font-size: px2vh(42);
                  span {
                    color: #ff4355;
                  }
                }
                .delete-icon {
                  position: absolute;
                  top: px2vw(-20);
                  right: px2vw(-20);
                  width: px2vw(40);
                  height: px2vw(40);
                  background-color: rgba(0, 0, 0, 0.7);
                  border-radius: 50%;
                  color: #fff;
                  display: flex;
                  justify-content: center;
                  align-items: center;
                }
              }
            }
          }
          .image-ready-wrap {
            // width: 100%;
            display: flex;
            padding: 0 px2vh(30) 0;
            flex-wrap: wrap;
            .image-item {
              padding: 0 px2vh(15) px2vh(60);
              box-sizing: border-box;
              position: relative;
              img {
                width: px2vw(230);
                height: px2vw(230);
                border-radius: px2vw(6);
              }
              .small-title {
                position: absolute;
                width: px2vw(230);
                text-align: center;
                // bottom: px2vh(-46);
                font-size: px2vh(30);
                color: #dbdbdb;
              }

            }
          }
          .signintitle {
            flex-direction: column;
            font-size: px2vh(42);
            color: #666666;
            padding-bottom: px2vh(54);
            box-sizing: border-box;
            .notes {
              padding: px2vh(40) 0;
              box-sizing: border-box;
              border-bottom: 2px dashed #f2f6fa;
              margin: 0 px2vh(50) 0;
              span {
                color: #ff4355;
              }
            }
            .notes-tips {
              width: 80%;
              display: flex;
              align-items: center;
              justify-content: flex-start;
              margin: px2vh(50) 0  px2vh(50) px2vh(50);
              .tips-item {
                margin-right: px2vw(30);
                padding: px2vh(18) px2vw(50);
                color: #417ADC;
                background: rgba(65,122,220,0.1);
                border-radius: 6px;
                border-radius: 6px;
                font-size: 13px;
                font-weight: normal;
                &.active {
                  color: #FFFFFF;
                  background: #417adc;
                }
              }
            }
            .notestext {
              background-color: #fafafa;
              margin: 0 px2vh(50);
              /deep/.van-cell {
                background-color: #fafafa;
              }
            }
          }
          .equipmenttitle {
            font-size: px2vh(42);
            color: #666666;
            padding: px2vh(42) px2vh(49);
            box-sizing: border-box;
          }
        }
      }
      .isledger {
        height: px2vh(167);
        margin-bottom: px2vh(30);
        /deep/.van-cell {
          height: px2vh(167);
          align-items: center;
          color: #666666;
          font-size: px2vh(42);
          font-weight: 700;
        }
      }
    }
  }
  footer {
    flex-shrink: 0;
    height: px2vh(155);
    background: #f2f6fa;
    padding-top: px2vh(45);
    /deep/ .van-button {
      width: calc(100% - #{px2vw(60)});
      margin-left: px2vh(30);
      height: px2vh(120);
      color: #fff;
      background-color: #417adc;
      border: 1px solid #417adc;
      border-radius: px2vh(60);
    }
  }
}

.van-preview-wrap {
      width: 100%;
      height: 100%;
      display: flex;
      align-items: center;
      .van-swipe {
        width: 100%;
        height: 60%;
        .van-swipe-item {
          display: flex;
          align-items: center;
          img {
            width: 100%;
          }
        }
      }
}
.van-popup {
  background-color: #eee;
  .van-cell {
    position: absolute;
    bottom: 0;
    border-top: 4px solid #eee;
    z-index: 3;
  }
}
</style>
